// 
//  Copyright © 2009 Jiří Zárevúcky <zarevucky.jiri@gmail.com>
// 
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Affero General Public License as
//  published by the Free Software Foundation, either version 3 of the
//  License, or (at your option) any later version.
// 
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Affero General Public License for more details.
// 
//  You should have received a copy of the GNU Affero General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
// 
// 


using System;
using System.Reflection;
using System.IO;
using System.Collections.Generic;

using Anculus.Core;

using Galaxium.Protocol.Xmpp.Library.Xml;

namespace Galaxium.Protocol.Xmpp.Library.Extensions.Disco
{
	public class IdentityDescription {
		private static Dictionary<string, string> _category_descriptions;
		private static Dictionary<string, string[]> _type_descriptions;
		
		public string CategoryDescription { get; private set; }
		public string TypeDescription { get; private set; }
		public string TypeDoc { get; private set; }
		
		private static void DecodeCategory (object sender, ElementEventArgs e)
		{
			try {
				var name = e.Element.GetTextChild ("name", null);
				_category_descriptions [name] = e.Element.GetTextChild ("desc", null);
				foreach (var type in e.Element) {
					if (e.Element.Name != "type") continue;
					_type_descriptions [name + '/' + type ["name"]] = new string []	{
						type ["desc"], type ["doc"]
					};
				}
			}
			catch (Exception ex) {
				Log.Error (ex, "Invalid record in disco-categories.xml\n" +
				           Serializer.Serialize (e.Element));
			}
		}
		
		static IdentityDescription ()
		{
			_category_descriptions = new Dictionary<string, string> ();
			_type_descriptions = new Dictionary<string, string[]> ();
			
			var assembly = Assembly.GetAssembly (typeof (IdentityDescription));
			var stream = assembly.GetManifestResourceStream ("disco-categories.xml");
			var parser = new StreamParser ();
			parser.ElementParsed += DecodeCategory;
			var reader = new StreamReader (stream);
			parser.ParseBuffer (reader.ReadToEnd ().ToCharArray ());
		}
		
		public static IdentityDescription Get (string category, string type)
		{
			var category_desc = _category_descriptions.ContainsKey (category) ?
				_category_descriptions [category] : "Unknown category";
			var type_entry = _type_descriptions.ContainsKey (category + '/' + type) ?
				_type_descriptions [category + '/' + type] : new string[] { "Unknown type", "N/A" };
			return new IdentityDescription {
				CategoryDescription = category_desc,
				TypeDescription = type_entry [0],
				TypeDoc = type_entry [1] 
			};
		}
		
		private IdentityDescription ()
		{
		}
	}
}
